package com.cloudfun.campusshare.service.handler;

import com.cloudfun.campusshare.common.constant.OrderStatus;
import com.cloudfun.campusshare.common.constant.RefundReview;
import com.cloudfun.campusshare.common.model.dto.kjt.KjtNotifyBaseDTO;
import com.cloudfun.campusshare.common.model.dto.kjt.KjtRefundStatusSyncDto;
import com.cloudfun.campusshare.entity.OrderEntity;
import com.cloudfun.campusshare.entity.OrderRefundEntity;
import com.cloudfun.campusshare.repo.OrderEntityRepo;
import com.cloudfun.campusshare.repo.OrderRefundEntityRepo;
import com.cloudfun.campusshare.util.AmountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class KjtRefundStatusSyncHandler implements KjtNotifyHandler<KjtRefundStatusSyncDto> {


    @Autowired
    private OrderRefundEntityRepo refundEntityRepo;

    @Autowired
    private OrderEntityRepo orderEntityRep;

    /**
     * 要处理的通知类型
     *
     * @return
     */
    @Override
    public String notifyType() {
        return "refund_status_sync";
    }

    /**
     * 数据类型
     *
     * @return
     */
    @Override
    public Class<KjtRefundStatusSyncDto> notifyMessageType() {
        return KjtRefundStatusSyncDto.class;
    }

    /**
     * 处理
     *
     * @param notifyMsg
     * @return
     */
    @Override
    public boolean handle(KjtNotifyBaseDTO notifyMsg) {
        KjtRefundStatusSyncDto refundStatusSyncDto = (KjtRefundStatusSyncDto) notifyMsg;
        String orderNo = refundStatusSyncDto.getOuterTradeNo();
        String refundAmount = refundStatusSyncDto.getRefundAmount();
        int tradeAmount = AmountUtil.strAmount2Int(refundAmount);
        OrderRefundEntity orderRefundEntity = refundEntityRepo.findByOrderRefundNo(orderNo);
        if (tradeAmount != orderRefundEntity.getPrice()) {
            log.error("快捷通退款通知，退款金额：{}和订单金额：{}不匹配", tradeAmount, orderRefundEntity.getPrice());
            return false;
        }
        OrderEntity orderEntity = orderEntityRep.findByOrderNo(refundStatusSyncDto.getOrigOuterTradeNo());
        if (refundStatusSyncDto.getRefundStatus().equals("REFUND_SUCCESS")){
            orderEntity.setOrderStatus(OrderStatus.REFUND);
            orderRefundEntity.setRefundReview(RefundReview.SUCCESS);
            orderRefundEntity.setOrderStatus(OrderStatus.REFUND);
            orderRefundEntity.setRefundTime(refundStatusSyncDto.getGmtRefund());
        }else {
            orderRefundEntity.setRefundReview(RefundReview.FAIL);
            orderRefundEntity.setRemark(refundStatusSyncDto.getFailReason());
        }
        orderEntityRep.save(orderEntity);
        refundEntityRepo.save(orderRefundEntity);
        return true;
    }
}
